package com.stegniy.anagram;

import java.io.*;
import java.util.*;

public class WordsReader {

    static String fileName;
    static String fileNameOutput;

    public static void main(String[] args) throws FileNotFoundException {
        Scanner sc = new Scanner(System.in);
        if (sc.hasNextLine()) {
            fileName = sc.nextLine();
            fileNameOutput = sc.nextLine();

            String text = read(fileName);
            List<String> listWords = inputSplit(text);

            List<List<String>> anagram = new AnagramFinder().findAnagram(listWords);

            //System.out.println(anagram);

            //AnagramWriter.write("/home/cat/Рабочий стол/out.txt", anagram);
            AnagramWriter.write(fileNameOutput, anagram);
        }
    }

    public static String read(String fileName) throws FileNotFoundException {
        StringBuilder sb = new StringBuilder();

        exists(fileName);

        try {
            BufferedReader in = new BufferedReader(new FileReader(fileName));
            try {
                String s;
                while ((s = in.readLine()) != null) {
                    sb.append(s);
                    sb.append("\n");
                }
            } finally {
                in.close();
            }
        } catch(IOException e) {
            throw new RuntimeException(e);
        }

        return sb.toString();
    }

    private static void exists(String fileName) throws FileNotFoundException {
        File file = new File(fileName);

        if (!file.exists()){
            throw new FileNotFoundException(file.getName());
        }

        if (!file.isFile()) {
            throw new IllegalArgumentException(file.getName());
        }
    }

    public static List<String> inputSplit (String textFromFile) throws FileNotFoundException {
        String REGEXP = "[\\d\\s\\p{Punct}]";

        textFromFile = WordsReader.read(fileName);

        String[] words = textFromFile.split(REGEXP);
        List<String> wordsList = new ArrayList<String>();

        for (String w : words) {
            if ((w != " ")||(w != "")) {
                wordsList.add(w.toLowerCase());
            }
        }
        return wordsList;
    }
}
